import { useUserStore } from '@/store'
import { isLogin } from '@/utils/auth'

export default function setupUserLoginInfoGuard(router) {
  router.beforeEach(async (to, from, next) => {
    const { userInfo, info, logout } = useUserStore()
    if (isLogin()) {
      if (userInfo.user_id) {
        next()
      } else {
        try {
          await info()
          next()
        } catch (error) {
          await logout()
          next()
        }
      }
    } else {
      if (!to.mate?.requiresAuth) {
        next()
        return
      }
    }
  })
}
